<template>
  <div class="h100">
    <a-form-model
      :rules="rules"
      ref="formComp"
      :model="form"
      layout="horizontal"
      class="AsteriskAfter newEditStyle rightDrawerWithoutCol"
      style="display: flex; flex-direction: column"
    >
      <!-- 版本配置 -->
      <!--ECU  配置文件软件编码 -->
      <template v-if="!recordData.isDetail">
        <a-form-model-item :label="$t('groupVersionConfig')" class="customFormModelItem"/>
        <a-form-model-item >
        <a-row :gutter="36">
          <a-col :md="12" :sm="24">
            <a-form-model-item prop="ecuModuleId" label="ECU">
              <a-input-group compact>
                <car-model-code-select
                  :query="{ time:instantUpdateTime, selectAll: false}"
                  :has-all="false"
                  :disabled="!!recordData.id"
                  :clear="false"
                  :filterOption="$commonFun.filterOption"
                  v-model="form.modelCode"
                  style="width:30%"
                  @change="changeEcuListByCarModel"
                ></car-model-code-select>
                <a-select
                  v-model="form.ecuModuleId"
                  :disabled="!!recordData.id"
                  showSearch
                  allow-clear
                 :filterOption="$commonFun.filterOption"
                  @change="changeEcuList"
                  :placeholder="$t('pleaseSelect') + $t('lingjian')"
                  style="width:70%"

                >
                  <a-select-option
                    v-for="(item, index) in ecuList"
                    :key="index"
                    :value="item.ecuModuleId"
                    :title="!item.configSoftwareCode?`${item.name}/${item.ecuModuleId}`+' 无配置文件软件编码':`${item.name}/${item.ecuModuleId}`"
                  >
                    {{ `${item.name}/${item.ecuModuleId}` }}
                    <span v-if="!item.configSoftwareCode" style="color:red;padding-left: 10px">无配置文件软件编码</span>
                  </a-select-option>
                </a-select>
              </a-input-group>
            </a-form-model-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-model-item required :label="$t('configurationFileCode')">
              <span v-if="!form.configSoftwareCode" style="color:red">
                {{form.ecuModuleId ? 'ECU未设置配置文件软件编码' : '请选择ECU'}}
              </span>
              <span v-else>{{form.configSoftwareCode}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!--配置文件版本 兼容版本 -->
        <a-row :gutter="36">
          <a-col :md="12" :sm="24">
            <a-form-model-item prop="name">
              <span slot="label">
                {{ $t('configFileVersion') }}
                <question-mark-tip
                  :tip-title="$t('inputVersionNameWithoutVTip')"
                  :popupContainer="getPopupContainer"
                ></question-mark-tip>
              </span>
              <a-input :disabled="!!recordData.id" v-model="form.name"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item>
              <template slot="label">
                {{ $t('dependencyVersion') }}
                <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer">
                  <template slot="title">
                    <span>{{ $t('dependencyVersionTip') }}</span>
                  </template>
                  <a-icon type="question-circle" />
                </a-tooltip>
              </template>
              <VersionSelect v-model="selectedDependenceVersion" :clear="true" mode="multiple" onlyVersionType="TEST"
                             versionBelong="configFile"
                             :ecuModuleId="form.ecuModuleId"
                             :targetVersionId="recordData.id"
                             :replace-fields="{key:'name', value:'name',title:'name'}"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model-item>
      </template>
      <detail v-else title="groupVersionConfig">
        <detail-item :label="$t('vehicleModel')" :content="form.modelCode" label-width="80"/>
        <detail-item label="ECU" :content="selectedEcu ? selectedEcu.name : ''" label-width="80"/>
        <detail-item :label="$t('configurationFileCode')" :content="form.configSoftwareCode"  label-width="120"/>
        <detail-item :label="$t('configFileVersion')" :content="form.name"  label-width="120"/>
        <detail-item :content="selectedDependenceVersion.join('，')" label-width="80">
          <template #label>
            <table-ellipsis :tableEllipsisIsTurnLine="false" :text="$t('dependencyVersion')" widthContent="auto" style="display:inline-flex"/>
            <!-- <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer"> -->
              <template slot="title">
                <span>{{ $t('dependencyVersionTip') }}</span>
              </template>
              <!-- <a-icon type="question-circle" /> -->
            <!-- </a-tooltip> -->
          </template>
        </detail-item>
      </detail>
      <!-- 版本文件 -->
      <div style="position: relative">
        <a-form-model-item>
          <template slot="label">
            <h4 class="withVerticleLineT4 title12">
              {{ $t('versionFile') }}
              <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer">
                <template slot="title">
                  <span>{{ $t('configFileVersionFileTip') }}</span>
                </template>
                <a-icon type="question-circle" />
              </a-tooltip>
              <span class="requiredSty"/>
            </h4>
          </template>
        </a-form-model-item>
        <a v-if="!recordData.isDetail" style="position: absolute; left: 120px; top: 0" @click="addFiles">
          {{ $t('upload') }}
        </a>
      </div>
      <div class="">
        <a-table
          ref="table"
          size="default"
          :row-key="(record, index) => index"
          :columns="columns"
          :components="tableComponents"
          :data-source="fileList"
          :pagination="false"
          :scroll="{ x: 400, y: true }"
        >
          <template slot="fileName" slot-scope="text, record">
            <!-- 回显的 -->
            <table-ellipsis v-if="record.id" :text="record.name"></table-ellipsis>
            <!-- 新传的 -->
            <table-ellipsis v-else :text="record.fileName"></table-ellipsis>
          </template>
          <span slot="fileStatus">
            {{ $t('fileStatus') }}
            <question-mark-tip
              :tip-title="$t('pzwjztTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </span>
          <template slot="fileStatus" slot-scope="text, record">
            <table-ellipsis :text="fileStatus(record)"></table-ellipsis>
          </template>
          <template slot="zysf" slot-scope="text, record">
            {{ digestAlgorithm[record.hashAlgorithm] }}
          </template>
          <template slot="zyz" slot-scope="text, record">
            <a @click="showZyz(record)">{{ $t('view') }}</a>
          </template>
          <!-- 预计安装时间 -->
          <template slot="installTime" slot-scope="text">
            <table-ellipsis :text="text"></table-ellipsis>
          </template>
          <template slot="dllName" slot-scope="text">
            <table-ellipsis :text="dllNameDictCodeObj[text]"></table-ellipsis>
          </template>
        </a-table>
      </div>

      <!-- 零件信息 -->
      <div style="flex: 1 0 0; margin-top: 24px; display: flex; flex-direction: column">
        <a-form-model-item :label="$t('ecuInfo')" class="customFormModelItem"> </a-form-model-item>
        <div style="flex: 1 0 0">
          <parts-infor-list
            :refrenshTime="refrenshTime"
            :query="{ ecuModuleId: form.ecuModuleId || '' }"
          ></parts-infor-list>
        </div>
      </div>
    </a-form-model>
    <!-- 上传文件 -->
    <upload-config-version-file ref="uploadFile" @saveFile="uploadOk"></upload-config-version-file>
    <!-- 摘要值弹框 -->
    <summary-modal ref="summaryRef" :summaryValue="summaryValue"> </summary-modal>
  </div>
</template>
<script>
import { STable } from '@/components'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapState } from 'vuex'
import UploadConfigVersionFile from './UploadConfigVersionFile.vue'
import PartsInforList from '../../components/PartsInforList.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import SummaryModal from '@/views/components/SummaryModal.vue'
import lodash from 'lodash'
import { checkVersionNameWithOutV } from '@/utils/validate'
import tableDraggable from '@/utils/tableDraggable'
import { newEditconfigFilecolumns } from '../config'
import VersionSelect from '@/views/components/VersionSelect'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import ecuApi from '@/api/modules/system/ecuMana'
import EditItem from '@/components/EditItem'
import DetailItem from '@/components/detail/detailItem'
import Detail from '@/components/detail'

const initForm = {
  ecuModuleId: undefined,
  configSoftwareCode: undefined,
  name: undefined,
  dependenceVersion: undefined
}
export default {
  name: 'NewEditConfigFile',
  components: {
    Detail,
    DetailItem,
    EditItem,
    STable,
    tableEllipsis,
    UploadConfigVersionFile,
    PartsInforList,
    VersionSelect,
    QuestionMarkTip,
    SummaryModal,
    CarModelCodeSelect
  },
  data () {
    return {
      selectedDependenceVersion: [],
      columns: [...newEditconfigFilecolumns],
      tableComponents: {},
      tagApk: false, // false是自定义应用名称包名，true是apk解析
      rules: {
        ecuModuleId: [{ required: true, message: this.$t('pleaseSelect') }],
        // lxhmodifyxccode
        name: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: checkVersionNameWithOutV()
          }
        ],
      },
      form: lodash.cloneDeep(initForm),
      isSearch: false,
      selectedEcuList: [], // 已选中ecu
      ecuList: [],
      fileList: [],
      refrenshTime: 1, // 监听刷新零件信息
      summaryValue: '',
      modelName: undefined
    }
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      digestAlgorithm: (state) => state.dict.digestAlgorithm
    }),
    dllNameDictCodeObj () {
      return this.$store.getters.getDictCodeObj('dllNameDictCode')
    },
    fileStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('fileStatusDictCode')
    },
    resourceStateDictCodeObj () {
      return this.$store.getters.getDictCodeObj('resourceStateDictCode')
    },
    selectedEcu() {
      return this.ecuList.find(e => e.ecuModuleId === this.form.ecuModuleId);
    }
  },
  watch: {
    instantUpdateTime: {
      handler () {
        // this.initForm()
      },
      immediate: true
    },
    'form.modelCode'(val){
      this.$refs.formComp.clearValidate('ecuModuleId')
    },
    'form.ecuModuleId' (val) {
      const vm = this
      // 获取配置文件软件编码下拉数据
      if (!vm.recordData.id && val) {
        vm.form.configSoftwareCode = vm.ecuList.find(e => e.ecuModuleId === val).configSoftwareCode;
      }
      // 获取零件信息
      vm.refrenshTime = Date.now()
      // 获取兼容版本
      if (!vm.recordData.id) {
        // vm.$set(vm.form, 'dependenceVersion', undefined)
        vm.selectedDependenceVersion =  [];
      }
    }
  },
  created () {
    this.initForm()
    this.tableComponents = tableDraggable(this.columns)
  },
  mounted () {
    this.tableComponents = tableDraggable(this.columns)
    this.$store.dispatch('getDllNameDictCodeData')
    this.$store.dispatch('getFileStatusDictCodeData')
    this.$store.dispatch('getResourceStateDictCodeData')
  },
  methods: {
    getPopupContainer () {
      return document.body
    },
    // 初始化表单
    initForm () {
      const vm = this
      vm.fileList = [] // 初始化版本信息表格
      vm.$refs.formComp && vm.$refs.formComp.resetFields()
      if (vm.recordData.id) {
        //   编辑
        vm.$api.configFileDetail({ id: this.recordData.id }).then((res) => {
          const resultData = res.data
          vm.form = res.data
          if (resultData.dependenceVersion) {
            // vm.$set(vm.form, 'dependenceVersion', resultData.dependenceVersion.split(','))
            vm.selectedDependenceVersion =  resultData.dependenceVersion.split(',');
          }
          vm.fileList = [resultData.resource]
          vm.$api.getAllEcu({ ecuModuleId: vm.form.ecuModuleId }).then((res) => {
            vm.ecuList = [...res.data]
          })
        })
      } else {
        //   新增
        vm.form = lodash.cloneDeep(initForm)
      }
      this.columns= [...newEditconfigFilecolumns];
      if(!this.recordData.id || //新增不展示表单编号
        //编辑/详情， 测试版不展示表单编号
        vm.recordData.versionType === 'TEST'){
        this.columns.splice(this.columns.length - 1, 1);
      }
    },
    // 保存提交验证
    getFormData () {
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate((valid) => {
          const vm = this
          if (!valid) {
            reject(valid)
            return
          }
          if (!vm.form.configSoftwareCode) {
            reject(valid)
            return
          }
          if (!this.fileList.length) {
            this.$message.warning(vm.$t('qscbbwj'));
            reject(new Error(vm.$t('qscbbwj')));
            return;
          }
          resolve(vm.getFormDataFun())
        })
      })
    },
    getFormDataFun () {
      const vm = this
      let resultP = {}
      if (vm.form.id) {
        resultP.id = vm.form.id
        resultP.apiStr = 'editConfigFile'
      } else {
        resultP = Object.assign(vm.form, { apiStr: 'addConfigFile' })
      }
      resultP.resourceId = this.fileList[0].resourceId
      if (vm.selectedDependenceVersion && vm.selectedDependenceVersion.length) {
        resultP.dependenceVersion = vm.selectedDependenceVersion.join(',')
      } else {
        resultP.dependenceVersion = ''
      }
      return resultP
    },
    // 获取已选中ecu的下拉数据
    changeEcuList (value) {
      const vm = this
      vm.selectedEcuList = []
      if (value) {
        const selectItem = vm.ecuList.filter((item) => item.ecuModuleId === value)
        vm.selectedEcuList = selectItem
      } else {
        // vm.ecuList = []
        vm.form.configSoftwareCode = undefined
      }
      this.$refs.formComp.validateField('ecuModuleId')
    },
    // 获取零件选项
    getEcuList (value) {
      const vm = this
      vm.ecuList = []
      vm.isSearch = false
      if (value) {
        vm.isSearch = true
        vm.$api.getAllEcu({ name: value.trim(), containConfigSoftwareCode: true }).then((response) => {
          vm.ecuList = response.data || []
        })
      } else {
        vm.ecuList = vm.selectedEcuList
      }
    },
    // 添加文件
    addFiles () {
      const vm = this
      if (this.fileList[0] && this.fileList[0].approved) {
        this.$message.warning(vm.$t('approvedTip'))
        return
      }
      this.$refs.uploadFile.addFiles()
    },
    // 上传提交
    uploadOk (formUploadFile) {
      this.fileList = [formUploadFile]
    },
    fileStatus (record) {
      let str = ''
      //  已认可
      if (record.approved) {
        str = this.$t('ApproveYes')
      } else {
        str = record.file ? this.fileStatusDictCodeObj[record.file.status] : this.$t('uploadedSuccessfully')
        // 加密情况
        str =
          str +
          `(${record.resourceState ? this.resourceStateDictCodeObj[record.resourceState] : this.$t('unencrypted')})`
      }

      return str
    },
    // 展示摘要值
    showZyz (record) {
      this.summaryValue = record.checksum
      this.$refs.summaryRef.visible = true
    },
    changeEcuListByCarModel(value) {
        this.form.ecuModuleId=undefined
        this.form.configSoftwareCode=undefined
        // 根据车型ID获取ecu列表
        ecuApi.getEcuListByModelCode({ "code":value }).then(res => {
          this.ecuList = res.data
        })
    }
  }
}
</script>
